package org.jypj.dev.controller;

import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.jypj.dev.constant.JpushConstant;
import org.jypj.dev.model.CodeData;
import org.jypj.dev.model.CommonMessage;
import org.jypj.dev.model.User;
import org.jypj.dev.service.ICodeDataService;
import org.jypj.dev.service.ICommonMessageService;
import org.jypj.dev.service.IUserService;
import org.jypj.dev.util.DateUtils;
import org.jypj.dev.util.JpushClientUtil;
import org.jypj.dev.util.StringUtil;
import org.jypj.dev.vo.hxVo.PushObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ChenYu on 2017-06-01.
 * 公共通知：普通消息
 */
@Controller
@RequestMapping("comMsgController")
public class ComMsgController {

    @Resource
    private ICommonMessageService commonMessageService;

    @Resource
    private IUserService userService;

    @Resource
    private ICodeDataService codeDataService;

    /**
     * 跳转到消息主页#普通消息
     *
     * @return
     */
    @RequestMapping(value = "toMsgMain.action")
    public String toMsgMain() {

        return "back/message/message_main";
    }

    /**
     * 查询单系列消息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "showMsg.action")
    public Map<String, Object> showMsg(String receiverName) {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        int code = 0;
        try {
            queryMap.put("receiverName", receiverName);
            List<CommonMessage> commonMessages = commonMessageService.selectAllByMap2(queryMap);
            String receiverUser = commonMessages.get(0).getReceiverUser();
            String receiverDep = commonMessages.get(0).getReceiverDep();
            List<CodeData> deps = getDepsByReceiverDep(receiverDep);
            List<User> users = getUsersByReceiverUser(receiverUser);
            dataMap.put("deps", deps);
            dataMap.put("users", users);
            dataMap.put("msgs", commonMessages);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 查询所有消息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectAllMsg.action")
    public Map<String, Object> selectAllMsg() {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        int code = 0;
        try {
            List<CommonMessage> commonMessages = commonMessageService.selectAllByMap(queryMap);
            dataMap.put("tableData", commonMessages);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 发送消息
     *
     * @param msg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "sendMsg.action")
    public Map<String, Object> sendMsg(String msg) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        try {
            String todayString = DateUtils.getTodayString("yyyy-MM-dd HH:mm:ss");
            Gson gson = new Gson();
            CommonMessage commonMessage = gson.fromJson(msg, CommonMessage.class);
            setReceiverUserDep(commonMessage);
            //保存到数据库
            commonMessage.setCreateTime(todayString);
            commonMessageService.saveCommonMessage(commonMessage);
            pushMsg(commonMessage);

        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }

        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 通过用户ID列表得到listUser
     *
     * @param receiverUser
     * @return
     */
    public List<User> getUsersByReceiverUser(String receiverUser) {
        List<User> users = new ArrayList<>();
        if (StringUtil.isEmpty(receiverUser)) {
            return users;
        }
        String[] split = receiverUser.split(",");
        for (String s : split) {
            User user = userService.selectUserById(s);
            users.add(user);
        }
        return users;
    }

    /**
     * 通过
     *
     * @param receiverDep
     * @return
     */
    public List<CodeData> getDepsByReceiverDep(String receiverDep) {
        List<CodeData> deps = new ArrayList<>();
        if (StringUtil.isEmpty(receiverDep)) {
            return deps;
        }
        String[] split = receiverDep.split(",");
        for (String s : split) {
            CodeData bmgl = codeDataService.selectCodeDataByItemValue("bmgl", s);
            deps.add(bmgl);
        }
        return deps;
    }

    public void setReceiverUserDep(CommonMessage commonMessage) {
        Set<String> receivers = new TreeSet<>();
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        List<User> users = commonMessage.getUsers();
        List<CodeData> deps = commonMessage.getDeps();
        for (CodeData dep : deps) {
            sb1.append(dep.getItemValue() + ",");
            receivers.add(dep.getItemText());
        }
        for (User user : users) {
            sb2.append(user.getId() + ",");
            receivers.add(user.getUsername());
        }
        commonMessage.setReceiverDep(sb1.toString());
        commonMessage.setReceiverUser(sb2.toString());
        String join = StringUtils.join(receivers, ",");
        commonMessage.setReceiverName(StringUtil.isEmpty(join) ? "全体成员" : join);
    }

    /**
     * 根据message对象推送消息
     *
     * @param commonMessage
     */
    public void pushMsg(CommonMessage commonMessage) {
        try {
            List<User> users = commonMessage.getUsers();
            List<CodeData> deps = commonMessage.getDeps();
            PushObject pushObject = new PushObject(JpushConstant.SEND_MSG, commonMessage.getSendUser() + "通知", commonMessage.getContent(), null);
            //保存到数据库
            if (users.size() == 0 && deps.size() == 0) {//表明是推送给全体用户
                JpushClientUtil.sendSelfMessageToAllAndroid(pushObject.toString());
            }
            Set<String> aliasFromList = getAliasFromList(users, deps);
            Set<String> tagsFromList = getTagsFromList(deps);
            if (aliasFromList.size() > 0) {
                JpushClientUtil.sendSelfMessageToManyByAlias(aliasFromList, pushObject.toString());
                System.out.println("推送人员：" + StringUtils.join(aliasFromList, ","));
            }
            if (tagsFromList.size() > 0) {
                JpushClientUtil.sendSelfMessageToManyByTags(tagsFromList, pushObject.toString());
                System.out.println("推送标签：" + StringUtils.join(tagsFromList, ","));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从选取的目标中得到需要推送用户的别名
     *
     * @param users
     * @param deps
     * @return
     */
    public Set<String> getAliasFromList(List<User> users, List<CodeData> deps) {
        Set<String> alias = new HashSet<>();
        String depStr = "";
        StringBuffer sb = new StringBuffer(depStr);
        for (CodeData cd : deps) {
            sb.append(cd.getItemValue() + ",");
        }
        for (User user : users) {
            if (!depStr.contains(user.getDepNum())) {
                alias.add(user.getUserNum());
            }
        }
        return alias;
    }

    /**
     * 得到选取的标签
     *
     * @param deps
     * @return
     */
    public Set<String> getTagsFromList(List<CodeData> deps) {
        Set<String> tags = new HashSet<>();
        for (CodeData dep : deps) {
            tags.add(dep.getItemValue());
        }
        return tags;
    }

}
